package cn.bnuz.edu.liyang.wait_eat_what;


import android.os.StrictMode;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import okhttp3.OkHttpClient;

public class ThingDB {
    private static String target = "http://192.168.123.160:8080/show?tag=";


    public static List getThingsList(int tag,
                                     int id,
                                     String name,
                                     String storeName,
                                     String type,
                                     boolean condition){
        target+=tag;
        switch (tag){
            case 1:
                target += "&name=" + name;
                break;
            case 2:
                target += "&id=" + id;
                break;
            case 3:
                target += "&type=" + type;
                break;
            case 4:
            case 5:
                target += "&storeName=" + storeName;
                break;
            case 6:
                target += "&type=" + type + "&condition="+condition;
                break;
            default:
                break;
        }
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        StringBuilder res = new StringBuilder();
        URL url;
        try {
            url = new URL(target);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            InputStreamReader reader = new InputStreamReader(httpURLConnection.getInputStream());
            BufferedReader br = new BufferedReader(reader);
            String inputLine = null ;
            while ((inputLine = br.readLine()) != null) {
                res.append(inputLine);
            }
            String result = res.toString();
            Gson gson = new Gson();
            if (tag == 5){
                String[] str = result.replace("\"","").replace("[","").replace("]","").split(",");
                List<String> list = new ArrayList<>();
                Collections.addAll(list,str);
                reader.close();
                httpURLConnection.disconnect();
                return list;
            }
            else {
                List<Things> list = gson.fromJson(result, new TypeToken<List<Things>>(){}.getType());
                reader.close();
                httpURLConnection.disconnect();
                return list;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
